class Tokens < Application
  before :find_token, :exclude => [ :new, :create, :index ]
  before :find_place

  def show
    only_provides :atom
    CGI::unescapeHTML(@token.to_atom.to_s)
  end
	
  def create
    provides :html, :atom
		
    case content_type
    when :html
      @place.tokens.create!({:value => params["token_to_add"]})

      self.headers[:Location] = request.referer
      self.status = 301
      return ""
    when :atom
      begin
        e = Atom::Entry.parse(request.raw_post, Merb::Config[:root]+request.path_info)
        token = tokens.create!(:value => CGI.unescapeHTML(e.content.to_s))
        head["Location"] = token.url
        return ""
      rescue Atom::ParseError
        self.status = 400
        return ""
      end
    end
  end
  
  def update
    if Merb::Config[:use_reevaluation]
      #trigger re-evaluation when token is edited from outside
      @token.case.execution_log.roll_back(@token)
    end
    @token.update_attributes!(params[:token])
    self.status = 200
    return ""
  end
	
  def delete
    only_provides :atom
    @place.tokens.delete(self)
    @token.destroy
  end
	
  private
  def find_place
    @place = PNEngine::Place.find(params[:place_id])
  end
	
  def find_token
    @token = PNEngine::Token.find(params[:id])
  end
end